<?php

namespace app\index\model;

use think\Db;
use think\Model;

class Login extends Model{
    protected $table = 'user';
    function login(){
        $input = input();
        $validate = new \app\index\validate\Login();
        if(!$validate->check($input)){
            throw new \Exception($validate->getError());
        }
        $user= $this->getByLogin($input['login']);
        $id = $user['id'];
        if (empty($user)) {
            throw  new \Exception("账号不存在！");
        }
        if ($user['password'] != $input['password']) {
            throw  new \Exception("密码错误！");
        }
        $bb=Db::query('select * from integral JOIN user ON u_id=user.id WHERE u_id = ?',[$id]);
        if (empty($bb[0]['integral'])){
            $bb[0]['integral']=0;
            $ss=Db::name('integral')->where('u_id',$id)->find();
            if(empty($ss)){
                $data=['integral'=>0,'u_id'=>$id];
                Db::name('integral')->insert($data);
            }
        }
        $rule=Db::name('htvip_rule')->select();
        $data=[];
        foreach ($rule as $re){
            $data[] = $re['consume'];
            $datas[] = $re['grade'];
        }
        for ($aa=0;$aa<count($data);$aa++){
            if ($bb[0]['integral']-$data[$aa]>=0){
                $reee =  $datas[$aa];
            }
        }
        if(empty($reee)){
            $reee=0;
        }
        Db::name('user')->where('id',$id)->update(['grade' =>$reee]);
        $a=User::get($id);
        return $a;
    }
}
